import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/api/common_service.dart';

import 'dart:async';

import 'package:wanandroid_flutter/model/wxarticle_content_model.dart';
import 'package:wanandroid_flutter/model/wxarticle_title_model.dart';
import 'package:wanandroid_flutter/utils/timeline_util.dart';
import 'package:wanandroid_flutter/utils/router_push_util.dart';

class WxArticlePage extends StatefulWidget {
  _WxArticlePageState createState() => _WxArticlePageState();
}

class _WxArticlePageState extends State<WxArticlePage>
    with TickerProviderStateMixin {
  List<WxArticleTitleData> _datas = List();
  TabController _tabController;

  void initState() {
    super.initState();
    _getData();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  /// ===================================================

  @override
  Widget build(BuildContext context) {
    _tabController = TabController(vsync: this, length: _datas.length);

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).accentColor,
        title: TabBar(
          controller: _tabController,
          tabs: _datas
              .map((WxArticleTitleData item) => Tab(text: item.name))
              .toList(),
          indicatorColor: Colors.white,
          isScrollable: true,
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: _datas
            .map((WxArticleTitleData item) => NewsList(ids: item.id))
            .toList(),
      ),
    );
  }

  /// ====================================================

  Future<Null> _getData() async {
    CommonService().getWxList((WxArticleTitleModel wxArticleTitleModel) {
      setState(() {
        _datas = wxArticleTitleModel.data;
      });
    });
  }
}

class NewsList extends StatefulWidget {
  final int ids;
  @override
  NewsList({Key key, this.ids}) : super(key: key);
  _NewsListState createState() => _NewsListState();
}

class _NewsListState extends State<NewsList>
    with AutomaticKeepAliveClientMixin {
  List<WxArticleContentDatas> _datas = List();
  ScrollController _scrollController = ScrollController();
  int _page = 1;
  bool _isAllData = false;

  void initState() {
    _getData();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        print('滑动到了最底部');

        _getMore();
      }
    });
    super.initState();
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  // ========================================

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
        onRefresh: _getData,
        child: ListView.builder(
          padding: const EdgeInsets.all(16.0),
          itemBuilder: _renderRow,
          itemCount: _datas.length + 1,
          controller: _scrollController,
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index < _datas.length) {
      return _newsRow(_datas[index]);
    }
    if (!_isAllData) return _getMoreWidget();
    return null;
  }

  Widget _getMoreWidget() {
    return Container(
      padding: const EdgeInsets.all(16.0),
      alignment: Alignment.center,
      child: SizedBox(
        width: 24,
        height: 24,
        child: CircularProgressIndicator(
          strokeWidth: 2,
        ),
      ),
    );
  }

  Widget _newsRow(WxArticleContentDatas item) {
    return InkWell(
      onTap: () {
        RouterPush.toWebview(context, item.title, item.link);
      },
      child: Card(
        child: Column(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: Text(
                      item.title,
                      style: TextStyle(
                          fontSize: 16.0, fontWeight: FontWeight.bold),
                      textAlign: TextAlign.left,
                    ),
                  ),
                ],
              ),
            ),
            Container(
              padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Expanded(
                    child: Text(
                      TimelineUtil.format(item.publishTime),
                      style: TextStyle(fontSize: 12.0, color: Colors.grey),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // =======================================

  Future<Null> _getData() async {
    _page = 1;
    int _ids = widget.ids;
    CommonService().getWxArticleList(
        (WxArticleContentModel wxArticleContentModel) {
      setState(() {
        if (wxArticleContentModel.data.datas.length < 20) {
          _isAllData = true;
        }
        _datas = wxArticleContentModel.data.datas;
      });
    }, _ids, _page);
  }

  Future<Null> _getMore() async {
    _page++;
    int _ids = widget.ids;

    CommonService().getWxArticleList(
        (WxArticleContentModel wxArticleContentModel) {
      setState(() {
        if (wxArticleContentModel.data.datas.length < 20) {
          _isAllData = true;
        }
        _datas.addAll(wxArticleContentModel.data.datas);
      });
    }, _ids, _page);
  }
}
